package com.dominator.serviceImpl;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.service.ApiMachineService;
import com.dominator.socket.WebSocketTools;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.exception.ApiException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApiMachineServiceImpl implements ApiMachineService {


    private RedisUtil ru = RedisUtil.getRu();


    @Override
    public ApiMessage machineLogin(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "machineId,sessionId");
        //机器码是否存在


        //redis保存
        Map<String, String> map = new HashMap<String, String>();
        map.put("sessionId", dto.getString("sessionId"));
        ru.hmsetEx("machine_" + dto.getString("machineId"), map,500);
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage machineLogout(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "machineId");
        ru.hdel("machine_" + dto.getString("machineId"), "sessionId");
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage sendToMachineId(Dto dto) throws ApiException {
        String sessionId = ru.hget("machine_" + dto.getString("machineId"), "sessionId");
        if (isMachineLogin(dto.getString("machineId"))){
            WebSocketTools.sendToId(ApiMessageUtil.success("发送内容"), sessionId);
        }else{
            throw new ApiException(ReqEnums.MACHINE_IS_NOT_LOGIN);
        }
        return ApiMessageUtil.success();
    }


    public boolean isMachineLogin(String machineId) {
        String res = ru.hget("machine_" + machineId, "sessionId");
        return SystemUtils.isNotEmpty(res);
    }
}
